/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 * 
 * @file:   Album.js
 * @path:   js-src/album/
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */

define(
    '../entrance_ticket/Ancestor',['require','exports','module'],function(require, exports, module) {
        window.Ancestor = window.Ancestor || {
            version: '1.0'
        };
        window.SystemDialog = (function () {
            var doHandler = null;
            var _initAlert = false;
            var _initConfirm = false;

            function initAlertDlg() {
                if (!_initAlert) {
                    if ($("#epg_alert_dlg").length == 0) {
                        $('body').append('<div id="epg_alert_dlg"><div sign="detail"></div></div>');
                    }
                    $("#epg_alert_dlg").dialog({
                        title: "epg系统提醒",
                        autoOpen: false,
                        width: 400,
                        modal: true,
                        dialogClass: 'alert',
                        resizable: false,
                        closeOnEscape:false,
                        buttons: [
                            {
                                text: "确认",
                                click: function () {
                                    $(this).dialog("close");
                                }
                            }
                        ]
                    })
                    _initAlert = true;
                }
                console.log("_initAlert:" + _initAlert);
            }

            function initConfirmDlg() {
                if (!_initConfirm) {
                    if ($("#epg_confirm_dlg").length == 0) {
                        $('body').append('<div id="epg_confirm_dlg"><div sign="detail"></div></div>');
                    }
                    $("#epg_confirm_dlg").dialog({
                        title: "epg系统确认",
                        autoOpen: false,
                        width: 400,
                        modal: true,
                        dialogClass: 'alert',
                        resizable: false,
                        closeOnEscape:false,
                        buttons: [
                            {
                                text: "确认",
                                click: function () {
                                    $(this).dialog("close");
                                    doHandler(true);
                                }
                            },
                            {
                                text: "取消",
                                click: function () {
                                    $(this).dialog("close");
                                    doHandler(false);
                                }
                            }
                        ]
                    });
                    $("div[aria-describedby=epg_confirm_dlg]").find("button:eq(1)").addClass("btn btn-primary");
                    $("div[aria-describedby=epg_confirm_dlg]").find("button:eq(2)").addClass("btn");
                    _initConfirm = true;
                }
                console.log("_initConfirm:" + _initConfirm);
            }

            function queryAlert(msg) {
                initAlertDlg()
                $("#epg_alert_dlg").find("div[sign=detail]").html(msg);
                $("#epg_alert_dlg").dialog("open");
            }

            function queryConfirm(msg, callback,btnNameObj) {
                initConfirmDlg();
                $("#epg_confirm_dlg").find("div[sign=detail]").html(msg);
                var btnExtend = $.extend(true,{"btn_ok":"确认","btn_cancel":"取消"},btnNameObj);
                if( "btn_ok" in btnExtend){
                    $("div[aria-describedby=epg_confirm_dlg]").find("button:eq(1)").html(btnExtend["btn_ok"])
                }
                if( "btn_cancel" in btnExtend){
                    $("div[aria-describedby=epg_confirm_dlg]").find("button:eq(2)").html(btnExtend["btn_cancel"])
                }
                $("#epg_confirm_dlg").dialog("open");
                doHandler = function (flag) {
                    if (typeof(callback) == "function") {
                        callback(flag);
                    }
                }
            }

            return {
                queryAlert: queryAlert,
                queryConfirm: queryConfirm
            }
        })();

    }
);
define(
    '../entrance_ticket/Ancestor.Auth',['require','exports','module'],function (require, exports, module) {
        Ancestor.Auth = (function () {
            var url = url || Com.url.parse(window.location.href)['path'];
            var baseInfo = {
                url: url,
                authUrl: '/api/permission',
                loginUrl: 'http://lego.iqiyi.com/login?url=http://lego.iqiyi.com%2F',
                url403: 'http://lego.iqiyi.com/common/403.jsp',
                loginOut: 'http://lego.iqiyi.com/logout',
                navListUrl: 'http://ulive.lego.iqiyi.com/live-web/services/liveNav.do',
                authInfo: null,
                tips: 0 //0 304页面提示 1头部标签提示
            }
            var jump2TargetPage = function (url) {
                window.location.href = url;
            }
            var getDev = function () {
                return parseInt(Com.cookie.get('dev'));
            };

            function getVersion(){
                return "4.3.172";
            }

            function setWaring(tips) {
                var warning = '<div  style="display:block;position: fixed;top: 5px;left: 10%;width: 80%;z-index: 100000;text-align: center;height: 26px;line-height: 26px;color: red;background: #fff1d3;margin-bottom: 16px;text-shadow: 0 1px 0 rgba(255,255,255,0.5);"><strong>提示!</strong> ' + tips + '</div>';
                return warning;
            }

            // ajax 请求
            var getAuthData = function (options, callback) {
                options = options || {};
                var tempBaseInfo = $.extend(true, baseInfo, options);
                Ancestor.Dao.ajax({
                    url: tempBaseInfo.authUrl,
                    dataType: 'json',
                    method: 'get',
                    cache: false,
                    //async: false,
                    data: {'uri': tempBaseInfo.url.split('?')[0]},
                    success: function (data) {
                        //console.log(data);
                        if (options.tips) {
                            //   if (baseInfo.tips) {
                            if (data.code == 'A00304')
                                callback.call(this, 1);   // 无权限
                            else
                                callback.call(this, null); // 有权限
                            return;
                        }
                        switch (data.code) {
                            case 'A00000': // 已登陆
                                tempBaseInfo.authInfo = data.data;
                                var newDev = 0;
                                if (tempBaseInfo.authInfo.devMode) {
                                    newDev = 1
                                }
                                var dev = getDev();
                                showLogInfo( baseInfo );
                                callback.call(this, "suc")
                                if (dev == NaN || dev != newDev) {
                                    Com.cookie.set('dev', newDev);
                                    window.location.reload();
                                }
                                break;
                            case 'A00303': // 未登陆
                            case 'A00401':
                                jump2TargetPage(tempBaseInfo.loginUrl);
                                break;

                            case 'A00304': // 无权限
                                //jump2TargetPage(baseInfo.url403);
                                var warning = setWaring('sorry,您没有操作本页面的权限！');
                                $('body').html('');
                                $('body').html(warning);
                                break;
                        }
                    },
                    error: function (data) {
                        var warning = setWaring('网络故障,<a href="javascript:void(0);" onclick = "window.location.reload();">请重刷！</a>');
                        $('body').html(warning);
                    }
                }, "/permission")

            }

            function queryNavList(baseInfo){
                var request = {};
                request.url = baseInfo.navListUrl;
                request.type = 'get';
                request.params = {};
                request.needCookie = true;
                request = JSON.stringify(request);
                Ancestor.Dao.redirectRequest({request: request} , function(data){
                    if(!data) {
                        console.warn(" 获取导航条失败!")
                        return;
                    }
                    var name, items, itemName, itemUrl;
                    var navListData = [];
                    for(var nav in data){
                        name = data[nav]['name'];
                        navListData.push('<dl class="panel-live_demand clearfix"><dt><strong>' + name + '</strong></dt><dd>');
                        items = data[nav]['items'];
                        for(var item in items){
                            itemName = items[item]['name'];
                            itemUrl = items[item]['url'];
                            navListData.push('<a href="' + itemUrl + '">' + itemName +'</a>')
                        }
                        navListData.push('</dd></dl>')
                    }
                    $('#panel-nav').html(navListData.join(''));
                } )
            }

            function showLogInfo(baseInfo) {
                var header = [
                    '<div class="top">',
                    '<div class="logo">',
                    '<a href="http://lego.iqiyi.com/" alt="乐高首页"></a>',
                    '</div>',
                    '<div class="user">',
                        '<input type="hidden" name="hidden_uid" value="' + baseInfo.authInfo.uid + '">',
                        ' Hi, <a href="" class="name">' + baseInfo.authInfo.userName + '</a>&nbsp;',
                    '[<a href="http://static.lego.iqiyi.com/help/lego-help-v1.docx" class="help">帮助</a>]&nbsp;',
                        '[<a href="' + baseInfo.loginOut + '" class="help">退出</a>]',
                    '</div>',
                    '</div>',
                    '<div class="nav">',
                    '<ol>',
                    '<li class="channel-index "><a href="http://ulive.lego.iqiyi.com/live-web/home.do" class="">我的首页</a><i></i></li>',
                    '<li class="channel-catalog selected"><a href="javascript:void(0)" class="selected">直播中心</a><i></i>',
                    '<div class="panel" id="panel-nav">',
                    '</div>',
                    '</li>',
                    '</ol>',
                    '</div>'
                ].join('');
                var epg_version = auth.version() + (auth.dev() ? "_test" : "_production");
                $("header").html(header);
                $('body').append('<div class="scroll-to-top scroll-to-top-hide" id="BackToTopButton"><a class="btn" href="#">返回顶部</a></div><footer>版本 ' + epg_version + ' | Copyright ©2017 <a href="http://www.iqiyi.com" target="_blank">iQIYI.com</a></footer>');
                $(window).bind('scroll', function () {
                    Com.page.scrollToTop($("#BackToTopButton"));
                });
                queryNavList(baseInfo)
            }

            return{
                getAuthData: getAuthData,
                baseInfo: baseInfo,
                jump2TargetPage: jump2TargetPage,
                dev: getDev, //开发环境
                version:getVersion
            };
        })();
        var auth = Ancestor.Auth;
        var dev = auth.dev();
        window.auth = auth;
        window.dev = dev;
        console.log(" window.auth done");
    }
);
/**
 * Copyright 2013 Qiyi Inc. All rights reserved.
 *
 * @file: Ancestor.Base.js
 * @path: js-src/Ancestor/
 * @desc: Ancestor模块下基础业对象类
 * @author: lichuning@qiyi.com
 * @date: 2013-04-10
 */
///import js-src/lib/
///import js-src/com/

define('../entrance_ticket/Ancestor.Grid',['require','exports','module'],function (require, exports, module) {

    Ancestor.Grid = function (options) {
    };
    /**
     * 每个Action都设置一个初始化方法 用于初始化Ancestor 原型对象，默认不重复初始化
     *
     * @param {Boolean}
     *            force 是否强制初始化
     *
     */
    Ancestor.Grid.prototype = $.extend(true, {}, Com.Grid, {
        /**
         * 素材库查询方法
         * @param params 查询参数，采用jquery formSerialize
         * @param callback
         */
        query: function (callback) {

            var self = this;
            var $grid = self.$grid;

            var params = this.getParam();

            $grid.jqGrid('setGridParam', {
                postData: params
            }).trigger('reloadGrid', [
                {
                    page: 1
                }
            ]);

        },
        getParam: function () {

            var self = this;
            var $container = self.options.$container;
            var $grid = self.$grid;
            Com.Grid.overridePostData($grid);
            var params = {};
            var $elements = $.makeArray($container.find('form.query').prop('elements'));

            $.each($elements, function () {
                if (this.name) {
                    var key = $(this).attr('data-key');
                    if (key) {
                        params[this.name] = $(this).attr(key) || '';
                    } else {
                        params[this.name] = $(this).val();
                    }
                }
            });

            return params;
        },

        echoQuery: function () {
            var self = this;
            var $container = self.options.$container;

            this.query();

        },

        getGridConfig: function (table, tableColModel) {
            var self = this;
            var tableConfig = $.extend(true, {}, table || self.config.TABLE);
            var colModel = tableConfig.colModel;
            var newColModel = [];
            var colModelConfig = tableColModel || self.config.TABLE_COLMODEL_CONFIG;

            $.each(colModel, function (i, model) {
                newColModel.push(colModelConfig[model]);
            });
            tableConfig.colModel = newColModel;
            return tableConfig;
        },

        initGrid: function (options, callback) {
            var self = this;

            var gridConfig = self.getGridConfig();

            var $gridContainer = self.options.$container;

            var type = self.getType();
            var $pager = $gridContainer.find('div.pager');
            var $grid = $gridContainer.find('table.grid');
            var params = self.getParam();
            options = $.extend(true, {
                pager: $pager,
                mtype: 'post',

                postData: $.extend(true, {
                    type: type

                }, params),

                sortname: 'createTime',
                sortorder: 'desc',


                multiselect: true,

                multiselectWidth: 30

            }, gridConfig, options);

            $grid.jqGrid('scroll', {});
            $grid.jqGrid(options);

        },

        reload: function (params) {
            var type = this.getType();
            params = $.extend(true, {
                type: type
            }, params);
            this.$grid.jqGrid('setGridParam', {
                postData: params
            }).trigger('reloadGrid');
        }


    })
});


/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Dao.js
 * @path:   js-src/Ancestor/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */
define('../entrance_ticket/Ancestor.Config',['require','exports','module'],function(require, exports, module) {


    ///import js-src/lib/
    ///import js-src/com/
    window.GLOBAL =   window.GLOBAL || {};
    GLOBAL.user = {
        area: "sh"
    };
    GLOBAL.currentDate = Com.date.getCurrentDate();

    Ancestor.Config = (function() {
        var EPG_AUTH = {
            From: 'frontend', // 来源
            key: '7dpHGKMy4hAh3DmC' // 密钥
        };
        return {
            EPG_AUTH: EPG_AUTH
        };
    })();

});
/**
 * @file:   Ancestor.Util.js
 * @path:   js/Ancestor/
 * @desc:
 * @author: karkarrotxu@qiyi.com
 * @date:   2017-08-15
 */
define('../entrance_ticket/Ancestor.Util',['require','exports','module'],function(require, exports, module) {


    ///import js-src/lib/
    ///import js-src/com/
    window.Ancestor = window.Ancestor || {
        version: '1.0'
    };
    Ancestor.Util = (function() {
        // 组装 sign
        var authorization = function(options) {
            var rawSign = options.url + options.clientTime + Ancestor.Config.EPG_AUTH.key;
            return md5(rawSign);
        };

        var getUrlId = function(name) {

            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null)
                return r[2];
            return null;
        };

        /**
         * 限制输入框中字符个数，一个汉字相当于两个字符，wordCount是最多允许的汉字个数
         * @param  {jquery  object}  $des  限制字符个数的输入框
         * @param  {Number}  wordCount     允许输入的最多汉字个数,默认为450个汉字
         * @param  {Boolean} isFilterChars 是否过滤输入内容，true过滤，false或undefined不过滤
         * @param  {Array}  filterChars    需要过滤的字符集，如['$','.']，意为全局过滤 $ *                                 和 .
         */
        var limitWordCount = function($des, wordCount, isFilterChars, filterChars) {
            wordCount = wordCount || 450;
            var t = function(textarea) {
                var $textarea = $(textarea);
                var text = $textarea.val();
                if (isFilterChars) {
                    // text = Com.string.filterSpecialChars(text, filterChars);
                    $textarea.val(text);
                }
                var length = Com.string.getStrLength(text);
                if (length > wordCount * 2) {
                    $textarea.val(Com.string.substrCn(text, wordCount));
                }
                text = $textarea.val();
                length = Com.string.getStrLength(text);
                $textarea.parent().find('span.leftWordsCount').text(wordCount - Math.round(length / 2));
            };
            $des.bind({
                input: function() {
                    t(this);
                },
                propertychange: function() {
                    t(this);
                },
                keyup: function() {
                    t(this);
                }
            });
            $des.keyup();
        };
        var getAuth = function(str) {

            var auth = {
                    'sign': '',
                    'clientTime': '',
                    'from': ''
                },
                time = parseInt(new Date().getTime() / 1000);

            auth.from = Ancestor.Config.EPG_AUTH.From;
            auth.clientTime = time;
            auth.sign = md5(str + time + Ancestor.Config.EPG_AUTH.key);

            //console.log(auth);            
            return auth;

        };

        return {
            authorization: authorization,
            getUrlId: getUrlId,
            limitWordCount: limitWordCount,
            getAuth: getAuth
        };
    })();

});
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Dao.js
 * @path:   js-src/Ancestor/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: jiegang@qiyi.com
 * @date:   2015-01-12
 */
define(
    '../entrance_ticket/Ancestor.Dao',['require','exports','module'],function(require, exports, module) {

        Ancestor.Dao = (function() {
            var ajax = function(options, authPath) {
                if (authPath)
                    $.ajax($.extend(options, {
                        beforeSend: function(request) {
                            var authBase = Ancestor.Util.getAuth(authPath);
                            request.setRequestHeader('Sign', authBase.sign);
                            request.setRequestHeader("Time", authBase.clientTime);
                            request.setRequestHeader("From", authBase.from);
                            request.setRequestHeader("UserName", (auth.baseInfo.authInfo==null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                        }
                    }));
                else
                    $.ajax(options);
            };

            // XMLHttp Request
            var _getXHR = function() {
                return new XMLHttpRequest() || new ActiveXObject('Msxml2.XMLHTTP') || new ActiveXObject('Microsoft.XMLHTTP');
            };

            var redirectRequest = function(options, callback) {
                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: options,
                    method: 'post',
                    beforeSend: function(request) {
                        var auth = Ancestor.Util.getAuth('/redirect');
                        request.setRequestHeader('Sign', auth.sign);
                        request.setRequestHeader("Time", auth.clientTime);
                        request.setRequestHeader("From", auth.from);
                    },
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, "/redirect");
            };

            return {
                redirectRequest: redirectRequest,
                ajax: ajax
            };
        })();
    }
);

define(
    '../epg2/EpgWeb',['require','exports','module'],function(require, exports, module) {
        window.EpgWeb = window.EpgWeb || {
            version: '1.0'
        };

        EpgWeb.Constant = {
            //baseApiUrl:"http://test.admin.epg.qiyi.domain/api/",
            baseApiUrl: "/api/",
            thirdUrl_audit_people: "http://lego.iqiyi.com/suggest/audit-people",
            originalUrl: "http://10.23.84.18:8500/",
            third_location_url:"http://lego.iqiyi.com/suggest/region",
            thirdUrl_qitan_url: "http://api.t.iqiyi.com/qx_api/resource/get_id_by_name",
            thirdUrl_add_qitan_url: "http://api.t.iqiyi.com/qx_api/resource/add_resource",
            thirdUrl_video_url: "http://lego.iqiyi.com/suggest/simple-video",
            thirdUrl_album_url: "http://lego.iqiyi.com/suggest/album",
            thirdUrl_playlist_url: "http://lego.iqiyi.com/suggest/playlist",
            thirdUrl_channel_url:"http://lego.iqiyi.com/apis/channel/list",
            thirdUrl_video_area_url: "http://lego.iqiyi.com/suggest/simple-video-area",
            thirdUrl_album_area_url: "http://lego.iqiyi.com/suggest/album-area",
            thirdUrl_apis_search_area_url: "http://lego.iqiyi.com/apis/search/search-area",
            thirdUrl_category_first_list_url:"http://lego.iqiyi.com/apis/category/live-first-list",
            // use for child secLv thirdLv
            thirdUrl_category_child_list_url: "http://lego.iqiyi.com/category/list",
            thirdUrl_passport_url:"http://passport.qiyi.domain/apis/internal/user_info.action",
            devMode: auth.dev()
        }
        EpgWeb.urlConfig = (function () {
            var useUrl = EpgWeb.Constant.baseApiUrl;
            var programListUrl = useUrl + "program/list";
            var programListSortUrl = useUrl + "program/listSort";
            var programAddUrl = useUrl + "program/add";
            var programDelUrl = useUrl + "program/delete";
            var programEditUrl = useUrl + "program/edit";
            var programLogUrl = useUrl + "program/loglist";
            var configsUrl = useUrl + "configs";
            var channelListUrl = useUrl + "channel/list";
            var programSyncUrl = useUrl + "program/syncTVMao";
            var redirectUrl = useUrl + "redirect";
            var channelGetUrl = useUrl + "channel/get";
            var queryPuYuUrl = useUrl + "program/queryPuYu";
            var carouselRuleListUrl = useUrl + "carousel/get";
            var carouselRuleDelUrl = useUrl + "carousel/del";
            var carouselRuldAddUrl = useUrl + "carousel/create";
            var programLiveQueryUrl = useUrl + "program/liveQuery";
            var programMoveUrl = useUrl + "program/move";
            var programToggleLockUrl = useUrl + "program/toggleLock";
            var programBatchAddUrl = useUrl + "program/batchAdd";
            var carouselEpisodeBatchAddUrl = useUrl + "carousel/carouselEpisode/batchAdd";
            var carouselEpisodeBatchDelUrl= useUrl + "carousel/carouselEpisode/batchDel";
            var carouselEpisodeListUrl= useUrl + "carousel/carouselEpisode/list";
            var carouselEpisodeIndexMoveUrl= useUrl + "carousel/carouselEpisode/indexMove";
            var carouselEpisodeIndexMoveByIndexUrl= useUrl + "carousel/carouselEpisode/indexMove/byIndex";
            var programDaySortUrl = useUrl + "program/daySort";
            var programIndexMoveUrl = useUrl + "program/indexMove";
            var programBatchDelUrl = useUrl + "program/batchDel";
            var platSettingsGetUrl = useUrl + "channel/getPlatSettings";
            var yesterdayEndTimeUrl = useUrl + "program/yesterdayEndTime";
            var automationAddUrl = useUrl + "carousel/automation/add";
            var automationDelUrl = useUrl + "carousel/automation/del";
            var automationListUrl = useUrl + "carousel/automations";
            var automationMoveUrl = useUrl + "carousel/automation/indexMove";
            var automationMoveByIndexUrl = useUrl + "carousel/automation/indexMove/byIndex";
            var automationChangeStatusUrl = useUrl + "carousel/automation/changeStatus";
            var getBroadcastControlsUrl = useUrl+"broadcast/controls";
            var reservation_create_Url = useUrl+ "reservation";
            var reservation_del_Url = useUrl+ "reservation/del";
            var reservation_edit_Url = useUrl+"reservation/edit";
            var reservation_get_Url = useUrl+ "reservations";
            var setBroadcastControlAllUrl= useUrl+"broadcast/controlall";
            var setBroadcastControlUrl  = useUrl+"broadcast/control";
            var platSettingsSaveUrl =  useUrl+"channel/savePlatSettings";
            var programBroadcastControlUrl =  useUrl+"program/broadcast/control";
            var programForceCheckUrl = useUrl + "program/forceCheck";
            var advertModifyUrl  = useUrl + "advert/modify";
            var directorCreateUrl =  useUrl + "director/create";
            var notifyAlertUrl = useUrl + "notify/alertPlatform";
            function getQiPuBaseUrl(qipuId){
                var plusUrl = EpgWeb.Constant.devMode ? "http://qipu-test.qiyi.domain/int/entity/nocache/@.json" : "http://qipu.qiyi.domain/int/entity/nocache/@.json";
                return plusUrl.replace("@", "" + qipuId);
            }
            return {
                programList: programListUrl,
                programListSortUrl: programListSortUrl,
                programAdd: programAddUrl,
                programDel: programDelUrl,
                programEdit: programEditUrl,
                programLog:programLogUrl,
                programForceCheck:programForceCheckUrl,
                configs: configsUrl,
                channelList: channelListUrl,
                channelGet: channelGetUrl,
                programSyncUrl: programSyncUrl,
                queryPuYu: queryPuYuUrl,
                carouselRuleListUrl: carouselRuleListUrl,
                carouselRuleDelUrl: carouselRuleDelUrl,
                carouselRuldAddUrl: carouselRuldAddUrl,
                carouselEpisodeBatchAddUrl:carouselEpisodeBatchAddUrl,
                carouselEpisodeBatchDelUrl:carouselEpisodeBatchDelUrl,
                carouselEpisodeListUrl:carouselEpisodeListUrl,
                carouselEpisodeIndexMoveUrl:carouselEpisodeIndexMoveUrl,
                carouselEpisodeIndexMoveByIndexUrl:carouselEpisodeIndexMoveByIndexUrl,
                programLiveQueryUrl: programLiveQueryUrl,
                programMoveUrl: programMoveUrl,
                programToggleLockUrl: programToggleLockUrl,
                programDaySortUrl: programDaySortUrl,
                programBatchAddUrl: programBatchAddUrl,
                programIndexMoveUrl: programIndexMoveUrl,
                programBatchDelUrl: programBatchDelUrl,
                platSettingsGetUrl: platSettingsGetUrl,
                yesterdayEndTimeUrl: yesterdayEndTimeUrl,
                automationAddUrl: automationAddUrl,
                automationDelUrl: automationDelUrl,
                automationListUrl: automationListUrl,
                automationMoveUrl: automationMoveUrl,
                automationChangeStatusUrl: automationChangeStatusUrl,
                reservationCreate:reservation_create_Url,
                reservationDel:reservation_del_Url,
                reservationGet:reservation_get_Url,
                getBroadcastControls:getBroadcastControlsUrl,
                reservationEdit:reservation_edit_Url,
                setBroadcastControlAllUrl:setBroadcastControlAllUrl,
                setBroadcastControl:setBroadcastControlUrl,
                platSettingsSaveUrl:platSettingsSaveUrl,
                programBroadcastControlUrl:programBroadcastControlUrl,
                redirect: redirectUrl,
                advertModifyUrl:advertModifyUrl,
                directorCreateUrl:directorCreateUrl,
                notifyAlertUrl:notifyAlertUrl,
                getQiPuBaseUrl:getQiPuBaseUrl
            }
        })();

        EpgWeb.ajaxQueue = (function () {
            var entity = this;
            var taskArr = [];
            var batchArr = [];
            var timerId = -1;
            var errorCollectArr = [];
            var afterCompleteArr = [];
            var status = -2;
            var checkComplete = function () {
                switch (status) {
                    case 1:
                        clearInterval(timerId);
                        timerId = -1
                        if (errorCollectArr.length > 0) {
                            var totalError = errorCollectArr.join("\n");
                            errorCollectArr = [];
                            EpgWeb.Plugin.showTips({
                                content: totalError,
                                type: "error"
                            })
                        }
                        status = 2;
                        loadComplete();
                        batchComplete();
                        break;
                    case -1:
                        $.each(taskArr, function (index, obj) {
                            if (obj.responseData == null) {
                                var ajaxData = obj.ajaxData;
                                $.ajax({
                                    type: ajaxData.type,
                                    url: ajaxData.url,
                                    dataType: ajaxData.dataType,
                                    beforeSend: function (request) {
                                        request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                                    },
                                    data: ajaxData.data,
                                    success: function (data) {
                                        var tempTarget = findTaskByRegName(obj.regName);
                                        if (tempTarget.needRemove == true) {
                                            removeTask(obj.regName);
                                        } else {
                                            tempTarget.responseData = data;
                                        }
                                        if (ajaxData.success != null) {
                                            ajaxData.success(data);
                                        }
                                    },
                                    error: function (data) {
                                        if (ajaxData.error != null) {
                                            ajaxData.error(data);
                                        }
                                        errorCollectArr.push(obj.regName + " 请求失败")
                                        removeTask(obj.regName)
                                    }
                                });
                            }
                        })
                        status = 0;
                        timerId = setInterval(checkComplete, 16);
                        break;
                    case 0:
                        var allComplete = true;
                        $.each(taskArr, function (index, obj) {
                            if (obj.responseData == null) {
                                allComplete = false;
                                return true;
                            }
                        });
                        if (allComplete) {
                            status = 1;
                        }
                        break;
                }
            }

            var batchComplete = function () {
                var tempArr = batchArr;
                batchArr =[];
                while (tempArr.length > 0) {
                    var batchRequestData = tempArr.pop();
                    batchRequestData.handler({"originalArr": batchRequestData.originalArr,
                            "acceptArr": batchRequestData.acceptMsgArr}
                    );
                }
            }

            var loadComplete = function () {
                console.log("loadComplete over");
                var tempArr = afterCompleteArr;
                afterCompleteArr = [];
                while (tempArr.length > 0) {
                    var excuteFunc = tempArr.shift();
                    excuteFunc.call();
                }
            }

            var push = function (regName, ajaxData, responseData, needRemove){
                if (typeof(needRemove) != "boolean") {
                    needRemove = needRemove == null ? false : true
                }
                taskArr.push({"regName": regName, "ajaxData": ajaxData, "responseData": responseData, "needRemove": needRemove})
            }

            var batchRequest = function (regName, ajaxData, sendDataArr, handler){
                var acceptMsgArr = [];
                var batchRequestData = {"originalArr": sendDataArr, "acceptMsgArr": acceptMsgArr, handler: handler }
                batchArr.push(batchRequestData)
                $.each(sendDataArr, function (index, obj) {
                    taskArr.push(
                        {
                            "regName": regName + "_" + index,
                            "ajaxData": {
                                type: ajaxData.type,
                                url: ajaxData.url,
                                dataType: ajaxData.dataType,
                                data: obj,
                                success: function (data) {
                                    var formatData = null;
                                    if (data != null) {
                                        formatData = {"nodeIndex": index, "operationSuccess": false, "responseData": data, "msg": data.msg};
                                        if (data.code == "A00000") {
                                            formatData.operationSuccess = true;
                                        }
                                    } else {
                                        formatData = {"nodeIndex": index, "error": true, "operationSuccess": false, "responseData": data};
                                    }
                                    acceptMsgArr.push(formatData)
                                },
                                error: function (data) {
                                    var formatData = {"nodeIndex": index, "error": true, "operationSuccess": false, "responseData": data};
                                    acceptMsgArr.push(formatData);
                                }
                            },
                            "needRemove": true
                        });
                })
            }

            var startLoad = function(){
                if (status != -2 && status != 2) {
                    return false;
                }
                status = -1;
                console.log(JSON.stringify(taskArr) );
                checkComplete();
                return true;
            }

            var findResponseData = function (regName) {
                var task = findTaskByRegName(regName);
                if (task == null) {
                    return null;
                }
                return task.responseData;
            }
            var removeTask = function (regName) {
                var task = findTaskByRegName(regName);
                if (task != null) {
                    var taskIndex = taskArr.indexOf(task)
                    taskArr.splice(taskIndex, 1);
                }
            }

            var findTaskByRegName = function(regName) {
                if (taskArr.length == 0) {
                    return null;
                }
                var returnTarget = null;
                $.each(taskArr, function (index, obj) {
                    if (obj.regName == regName) {
                        returnTarget = obj;
                        return false;
                    }
                })
                return returnTarget;
            }

            var afterLoadComplete = function (callback) {
                if (typeof(callback) == "function") {
                    afterCompleteArr.push(callback);
                }
            }

            var isRunning = function () {
                return status == 0;
            }

            function getTaskArr(){
                return [].concat(taskArr);
            }

            function getStatus(){
                return status;
            }

            return {
                startLoad:startLoad,
                findResponseData:findResponseData,
                findTaskByRegName:findTaskByRegName,
                batchRequest:batchRequest,
                push:push,
                isRunning:isRunning,
                removeTask:removeTask,
                afterLoadComplete:afterLoadComplete,
                getTaskArr:getTaskArr,
                getStatus:getStatus
            }
        })();
    }
);
define(
    '../epg2/EpgWeb.Util',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Util = $.extend(true, {}, Ancestor.Util, {
            tranDurationFormat: function (duration) {
                var darArr = [];
                darArr.push(duration % 60);
                duration = ( duration - duration % 60) / 60;
                if (duration > 0) {
                    darArr.push(duration % 60);
                }
                duration = ( duration - duration % 60) / 60;
                if (duration > 0) {
                    darArr.push(duration % 24);
                }
                duration = ( duration - duration % 24) / 24;
                if (duration > 0) {
                    darArr.push(duration);
                }
                var retValue = "";
                switch (darArr.length) {
                    case 4:
                        retValue = darArr[3] + "天";
                    case 3:
                        retValue += darArr[2] + "时";
                    case 2:
                        retValue += darArr[1] + "分";
                    case 1:
                        retValue += darArr[0] + "秒";
                        break;
                }
                return retValue;
            },
            makeUpRedirect: function (url, method, params, needCookie) {
                var requestData = {url: url, type: method, params: params};
                if (needCookie === true) {
                    requestData.needCookie = true;
                }
                return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
            },
            quickDateFormat: function (startTime) {
                return startTime.getFullYear() + "-" +
                    (startTime.getMonth() < 9 ? "0" + (startTime.getMonth() + 1) : (startTime.getMonth() + 1) ) + "-" +
                    (startTime.getDate() < 10 ? "0" + startTime.getDate() : startTime.getDate() );
            },
            bindDateMax: function (name1, name2, plusData) {
                $("input[name=" + name1 + "]").datetimepicker({
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        $("input[name=" + name2 + "]").datetimepicker("option", "maxDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + name2 + "]").datetimepicker("option", "maxDateTime", toDate);
                    }
                })
                if (plusData != null) {
                    $("input[name=" + name1 + "]").datetimepicker("option", "minDate", plusData.minDate);
                    $("input[name=" + name1 + "]").datetimepicker("option", "minDateTime", plusData.minDateTime);
                }
            },
            setZeroTime: function (checkTime) {
                checkTime.setSeconds(0);
                checkTime.setMinutes(0);
                checkTime.setHours(0);
                checkTime.setMilliseconds(0);
            },
            setDayLastTime: function (checkTime) {
                checkTime.setSeconds(59);
                checkTime.setMinutes(59);
                checkTime.setHours(23);
                checkTime.setMilliseconds(0);
            },

            bindDate: function (nameMin, nameMax, plusData) {
                var options1 = {
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        console.log("bindDate " +  selectedDate )
                        $("input[name=" + nameMax + "]").datetimepicker("option", "minDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + nameMax + "]").datetimepicker("option", "minDateTime", toDate);
                    }
                }
                var options2 = {
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        console.log("bindDate " +  selectedDate )
                        $("input[name=" + nameMin + "]").datetimepicker("option", "maxDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + nameMin + "]").datetimepicker("option", "maxDateTime", toDate);
                    }
                }
                if (plusData != null && plusData.hasOwnProperty("slider")) {
                    options1.controlType = "slider";
                    options2.controlType = "slider";
                }
                $("input[name=" + nameMin + "]").datetimepicker(options1)
                $("input[name=" + nameMax + "]").datetimepicker(options2)
                if (plusData != null) {
                    $("input[name=" + nameMin + "]").datetimepicker("option", "maxDate", plusData.maxDate);
                    $("input[name=" + nameMin + "]").datetimepicker("option", "maxDateTime", plusData.maxDateTime);
                    $("input[name=" + nameMax + "]").datetimepicker("option", "minDate", plusData.minDate);
                    $("input[name=" + nameMax + "]").datetimepicker("option", "minDateTime", plusData.minDateTime);
                }
            },



            bindDateMin: function (name1, name2, plusData) {
                $("input[name=" + name1 + "]").datetimepicker({
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        $("input[name=" + name2 + "]").datetimepicker("option", "minDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + name2 + "]").datetimepicker("option", "minDateTime", toDate);
                    }
                })
                if (plusData != null) {
                    $("input[name=" + name1 + "]").datetimepicker("option", "maxDate", plusData.maxDate);
                    $("input[name=" + name1 + "]").datetimepicker("option", "maxDateTime", plusData.maxDateTime);
                }
            },
            createPageBean: function () {
                return (function () {
                    var source = [];
                    var dataLength = source.length;
                    var rowNum = 10;
                    var total = (dataLength % rowNum == 0 ? 0 : 1) + parseInt(dataLength / rowNum);
                    var cur = 1;

                    function goToFirst() {
                        return goToUser(1);
                    }

                    function goToLast() {
                        return goToUser(total);
                    }

                    function goToUser(toPage) {
                        if (toPage < 1) toPage = 1;
                        if (toPage > total) toPage = total;
                        cur = toPage;
                        var end = cur * rowNum > dataLength ? dataLength : cur * rowNum;
                        var showData = source.slice((cur - 1) * rowNum, end);
                        return {"total": total, "page": cur, "records": dataLength, "rows": showData};
                    }

                    function getCur() {
                        return goToUser(cur);
                    }

                    function goNext() {
                        return goToUser(cur + 1);
                    }

                    function goPrev() {
                        return goToUser(cur - 1);
                    }

                    function setNewData(newData, newRowNum) {
                        source = newData == null ? [] : newData;
                        if (newRowNum != null && newRowNum > 0) {
                            rowNum = newRowNum;
                        }
                        dataLength = source.length;
                        total = (dataLength % rowNum == 0 ? 0 : 1) + parseInt(dataLength / rowNum);
                    }

                    function addNewOne(newOne) {
                        source.push(newOne);
                        setNewData(source, rowNum);
                    }

                    function delOne(delOne) {
                        var targetIndex = source.indexOf(delOne);
                        if (targetIndex > -1) {
                            source.splice(targetIndex, 1);
                            setNewData(source, rowNum);
                        }
                    }

                    function getSource() {
                        return [].concat(source);
                    }

                    function findData(keyName, value) {
                        var ret = null;
                        if (value == null || keyName == null) {
                            return null;
                        }
                        $.each(source, function (i, element) {
                            if (element != null && element[keyName] == value) {
                                ret = element;
                                return true;
                            }
                        })
                        return ret;
                    }

                    function sortData(func) {
                        if (typeof( func ) == "function") {
                            source.sort(func);
                        }
                    }

                    return {
                        goToFirst: goToFirst,
                        goToLast: goToLast,
                        goToUser: goToUser,
                        goNext: goNext,
                        goPrev: goPrev,
                        getCur: getCur,
                        setNewData: setNewData,
                        addNewOne: addNewOne,
                        delOne: delOne,
                        getSource: getSource,
                        findData: findData,
                        sortData: sortData
                    }
                })()
            },
            pageBeanPageHandler: function (gridId, pageId, pageBean, pgButton) {
                var retValue = null;
                switch (pgButton) {
                    case "next_" + pageId:
                        retValue = pageBean.goNext()
                        break;
                    case "prev_" + pageId:
                        retValue = pageBean.goPrev()
                        break;
                    case "last_" + pageId:
                        retValue = pageBean.goToLast()
                        break;
                    case "user":
                        retValue = pageBean.goToUser(parseInt($("#gbox_" + gridId + " .ui-pg-input").val()));
                        break;
                    case "first_" + pageId:
                        retValue = pageBean.goToFirst();
                        break;
                }
                return retValue
            },
            transGetParams: function (params) {
                var str = "";
                for (var key in params) {
                    str += key + "=" + params[key] + "&";
                }
                if (str.length > 0) {
                    str = str.substr(0, str.length - 1);
                }
                return str;
            },

            formatDateTimeFormat: function (myDate) {
                var year = myDate.getFullYear();
                var month = ("0" + (myDate.getMonth() + 1)).slice(-2);
                var day = ("0" + myDate.getDate()).slice(-2);
                var h = ("0" + myDate.getHours()).slice(-2);
                var m = ("0" + myDate.getMinutes()).slice(-2);
                var s = ("0" + myDate.getSeconds()).slice(-2);
                return year + "-" + month + "-" + day + " " + h + ":" + m + ":" + s;
            },
            getQueryComponent: function (handlerObj) {
                return {
                    source: null,
                    total: 0,
                    completeNum: 0,
                    handlerObj: handlerObj,
                    doInit: function (newArr) {
                        var self = this;
                        self.source = newArr;
                        self.total = newArr.length;
                        self.completeNum = 0;
                        self.doSubmit();
                    },
                    doSubmit: function () {
                        var self = this;
                        self.doBefore();
                        $.each(self.source, function (i, element) {
                            self.doSingle(element, function () {
                                self.notifyHandler()
                            });
                        })
                    },
                    doBefore: function () {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doBefore")) {
                                self.handlerObj.doBefore();
                            }
                        }
                    },
                    doAfter: function () {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doAfter")) {
                                self.handlerObj.doAfter();
                            }
                        }
                    },
                    doSingle: function (element, notifyHandler) {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doSingle")) {
                                self.handlerObj.doSingle(element, notifyHandler);
                            }
                        }
                    },
                    notifyHandler: function () {
                        var self = this;
                        self.completeNum++;
                        if (self.completeNum == self.total) {
                            self.doAfter();
                        }
                    }
                };
            },
            createWeekManager: function (labelArr) {
                return (function ($labelArr) {
                    var focusStartTime = null;
                    var selectDateTime = null;
                    var weekday = "星期日,星期一,星期二,星期三,星期四,星期五,星期六".split(",");

                    function preWeek() {
                        if (focusStartTime != null) {
                            updateWeek(new Date(focusStartTime.getTime() - 7 * 86400 * 1000));
                        }
                    }

                    function nextWeek() {
                        if (focusStartTime != null) {
                            updateWeek(new Date(focusStartTime.getTime() + 7 * 86400 * 1000));
                        }
                    }

                    function updateWeek(startTime) {
                        if (startTime != null) {
                            focusStartTime = startTime;
                        }
                        var tempStartTime = new Date(focusStartTime.getTime());
                        $labelArr.each(function (i, element) {
                            var lDateFormat = EpgWeb.Util.quickDateFormat(tempStartTime);
                            $(element).attr("query-date", lDateFormat);
                            $(element).removeClass("selected");
                            $(element).html(weekday[tempStartTime.getDay()] + "<br>" + lDateFormat);
                            if (lDateFormat == selectDateTime) {
                                $(element).addClass("selected");
                            }
                            tempStartTime.setTime(tempStartTime.getTime() + 86400 * 1000);
                        })
                    }

                    function quickToCurrentWeek() {
                        var current = new Date();
                        var currentIndex = -1;
                        if (current.getDay() == 0) {
                            currentIndex = 6;
                        } else {
                            currentIndex = current.getDay() - 1;
                        }
                        selectDateTime = EpgWeb.Util.quickDateFormat(current)
                        updateWeek(new Date(current.getTime() - currentIndex * 86400 * 1000));
                        //updateTableByDate(selectDateTime);
                        return selectDateTime;
                    }

                    return{
                        preWeek: preWeek,
                        nextWeek: nextWeek,
                        quickToCurrentWeek: quickToCurrentWeek
                    }
                })(labelArr)
            },
            createHeartBeatUtil: function () {
                return  (function () {
                    var params = {
                        startTime: 0,
                        isStarted: false,
                        indexId: 0,
                        dataArr: []
                    }

                    function doHeartBeat() {
                        var curTime = Date.now();
                        var cpArr = [].concat(params.dataArr);

                        $.each(cpArr, function (i, element) {
                            tick(element, curTime);
                        })
                    }

                    function start() {
                        if (params.isStarted) {
                            console.log("has started");
                            return;
                        }
                        params.startTime = Date.now();
                        params.isStarted = true;
                        $.each(params.dataArr, function (i, elment) {
                            elment.lastTime = params.startTime;
                        })
                        setInterval(function () {
                            doHeartBeat();
                        }, 160)
                    }

                    function tick(element, curTime) {
                        if (element.block || element.stop) {
                            return;
                        }
                        if (element.lastTime + element.gapTime < curTime) {
                            element.lastTime = curTime;
                            element.options.handler();
                            if (element.options.needBlock) {
                                element.block = true;
                            }
                        }
                    }

                    function pushTask(taskObj) {
                        params.indexId++;
                        var taskOptions = {
                            block: false,
                            stop: taskObj.stop || false,
                            options: taskObj,
                            id: params.indexId,
                            lastTime: 0
                        }
                        taskOptions.gapTime = accountGapTime(taskObj)
                        if (params.isStarted) {
                            taskOptions.lastTime = Date.now() + 100;
                        }
                        params.dataArr.push(taskOptions);
                        return taskOptions;
                    }

                    function accountGapTime(taskObj) {
                        var time = [0, 0, 0, 0];//ms,s,m,h
                        if ("ms" in taskObj.gap) {
                            time[0] = taskObj.gap.ms;
                        }
                        if ("s" in taskObj.gap) {
                            time[1] = taskObj.gap.s;
                        }
                        if ("m" in taskObj.gap) {
                            time[2] = taskObj.gap.m;
                        }
                        if ("h" in taskObj.gap) {
                            time[3] = taskObj.gap.h;
                        }
                        return  time[0] + time[1] * 1000 + time[2] * 60000 + time[3] * 3600000;
                    }

                    return {
                        start: start,
                        doHeartBeat: doHeartBeat,
                        pushTask: pushTask,
                        tick: tick
                    }
                })();
            },
            notifyAlert: function (sendData, handler) {
                EpgWeb.Dao.notifyAlert(sendData, function (rdata) {
                    handler(rdata)
                });
            },
            getCurrentUserEntity:function(){
                var ret = null;
                try{
                    ret =auth.baseInfo.authInfo;
                }catch (e){
                    console.warn(e);
                }
                return ret
            }
        });
    }
);
define(
    '../epg2/EpgWeb.Plugin',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Plugin = {
            showTips: function (options) {
                if (!options.hasOwnProperty("type")) {
                    options.type = "success";
                }
                if ($(document).tips != null) {
                    $(document).tips(options)
                }
                if ($(document).tip != null) {
                    $(document).tip(options)
                } else {
                    console.log("no tips plugin " + options);
                }
            },
            Validate: (function () {
                var reg1 = /^\d+$/;
                var reg3 = /^[1-9]\d*$/;
                var reg2 = /^(19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1]) ([0-2][0-9]):([0-5][0-9]):([0-5][0-9])$/;
                var reg4 = /^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/;
//                var _defaultHandler = function(msg){
//                    EpgWeb.Plugin.showTips({type: "error", content: msg})
//                }
                var _bindHandler = null;
                var checkObj = {
                    self_design: function (checkData, checkValue) {
                        return checkData.checkCall(checkData, checkValue)
                    },
                    date: function (checkData, checkValue) {
                        return checkDateFormat(checkValue);
                    },
                    not_empty: function (checkData, checkValue) {
                        return checkValue != null && $.trim(checkValue).length > 0;
                    },
                    eq: function (checkData, checkValue) {
                        return checkValue === checkData.other;
                    },
                    ne: function (checkData, checkValue) {
                        return checkValue !== checkData.other;
                    },
                    ge: function (checkData, checkValue) {
                        return  checkValue >= checkData.other;
                    },
                    gt: function (checkData, checkValue) {
                        return  checkValue > checkData.other;
                    },
                    lt: function (checkData, checkValue) {
                        return checkValue < checkData.other;
                    },
                    le: function (checkData, checkValue) {
                        return checkValue <= checkData.other;
                    },
                    positive:function(checkData, checkValue) {
                        return  checkPositive(checkValue)
                    },
                    number: function (checkData, checkValue) {
                        return checkNum(checkValue);
                    },
                    endsWith: function (checkData, checkValue) {
                        return checkValue != null && typeof(checkValue) == "string" && checkValue.slice(-(checkData.other.length)) == checkData.other;
                    }
                }

                function checkNum(checkString) {
                    return reg1.test(checkString)
                }

                function checkDateFormat(checkString) {
                    return reg2.test(checkString)
                }

                function checkPositive(checkString) {
                    return reg3.test(checkString)
                }

                function defaultHandler(msg) {
                    if(_bindHandler != null){
                        _bindHandler(msg);
                    }
                }

                function batchCheck(checkArr) {
                    if (checkArr == null) {
                        checkArr = [];
                    }
                    if (checkArr.length == 0) {
                        return true;
                    }
                    var flag = false;
                    $.each(checkArr, function (index, checkData) {
                        flag = baseCheck(checkData);
                        if (!flag) {
                            return false;
                        }
                    })
                    return flag;
                }

                function baseCheck(checkData) {
                    var flag = false;
                    //$.isArray(checkData.value )
                    if (!(checkData.value instanceof Array)) {
                        checkData.value = [checkData.value];
                    }
                    //$.isArray(checkData.error )
                    if (!(checkData.error instanceof Array)) {
                        checkData.error = [checkData.error];
                    }
                    if (checkData.handler == null) {
                        checkData.handler = defaultHandler;
                    }
                    $.each(checkData.value, function (index, checkValue) {
                        if (checkObj.hasOwnProperty(checkData.type)) {
                            flag = checkObj[checkData.type](checkData, checkValue);
                        }
                        if (!flag) {
                            var hint = checkData.error.length == checkData.value.length ? checkData.error[index] : checkData.error[0];
                            checkData.handler(hint);
                            return false;
                        }
                    })
                    return flag
                }
                function bindDefaultHandler(func){
                    _bindHandler = func;
                }
                return {
                    baseCheck: baseCheck,
                    batchCheck: batchCheck,
                    checkDateFormat: checkDateFormat,
                    checkNum: checkNum,
                    bindDefaultHandler:bindDefaultHandler
                }
            })(),

            tableToExcel: (function () {
                var uri = 'data:application/vnd.ms-excel;base64,',
                    template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
                    base64 = function (s) {
                        return window.btoa(unescape(encodeURIComponent(s)))
                    },
                    format = function (s, c) {
                        return s.replace(/{(\w+)}/g,
                            function (m, p) {
                                return c[p];
                            })
                    };

                return function (table, name) {
                    if (!table.nodeType) table = document.getElementById(table)
                    var ctx = {
                        worksheet: name || 'Worksheet',
                        table: table.innerHTML
                    }
                    window.location.href = uri + base64(format(template, ctx))
                }
            })()
        };

    }
);
define(
    '../epg2/EpgWeb.Dao',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Dao = $.extend({}, Ancestor.Dao, {
            cfgName: {
                LiveType: "LiveType",
                LogType: "LogType",
                episodeGradeType: "EpisodeGradeType",
                liveProgramType: "LiveProgramType",
                liveChannelType: "LiveChannelType",
                getChannel: "getChannel"
            },
            channelId: null,
            getDataByName: function (targetName) {
                var responseData = EpgWeb.ajaxQueue.findResponseData(targetName);
                return responseData;
            },
            sendAjax: function (url, method, data, callback, authUrl) {
                var options = {
                    url: url,
                    dataType: 'json',
                    data: data,
                    type: method,
                    success: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    },
                    error: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    }
                };
                Ancestor.Dao.ajax(options, authUrl);
            },
            appendAuthUrl: function (options, authUrl) {
                options = $.extend({},options, {
                    beforeSend: function (request) {
                        var authBase = Ancestor.Util.getAuth('/vod/episodeLogList');
                        request.setRequestHeader('Sign', authBase.sign);
                        request.setRequestHeader("Time", authBase.clientTime);
                        request.setRequestHeader("From", authBase.from);
                        request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                    }
                })
                return options;
            },

            sendProxy: function (options, headers) {
                $.ajax(this.transToProxyOptions(options, headers));
            },
            transToProxyOptions: function (options, headers) {
                var requestData = {url: options.url, type: options.type, params: options.data, needCookie: true};
                if (headers != null) {
                    requestData.headers = headers;
                }
                var newOptions = {
                    url: EpgWeb.urlConfig.redirect,
                    type: "post",
                    dataType: "json",
                    timeout: options.timeout?options.timeout: 5000,
                    data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                    success: function (data) {
                        options.success(data);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        options.error(null);
                    }
                }
                return newOptions;
            },
            doGet: function (url, data, callback) {
                var dataArr = [];
                for (var key in data) {
                    dataArr.push(key + "=" + data[key]);
                }

                var options = {
                    url: url,
                    dataType: 'json',
                    data: dataArr.join("&"),
                    type: 'get',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                $.ajax(options);
            },
            doAuthData: function (handlerObj) {
                if (auth == null) {
                    auth = Ancestor.Auth;
                }
                auth.getAuthData({tips: 1, url: handlerObj.url}, function (rt) {
                    if (rt == null) {
                        if (handlerObj.hasOwnProperty("doSuccess")) {
                            handlerObj.doSuccess();
                        }
                    } else {
                        if (handlerObj.hasOwnProperty("doError")) {
                            handlerObj.doError();
                        }
                    }
                    if (handlerObj.hasOwnProperty("doFinal")) {
                        handlerObj.doFinal();
                    }
                });
            },
//            checkJSVersion: function (data, callback) {
//                //method, data, callback, authUrl) {
//                this.sendAjax("/api/version/check", "post", {data:JSON.stringify(data)}, callback);
//            }
            notifyAlert: function (sendData, callback) {
                var url = EpgWeb.urlConfig.notifyAlertUrl;
                var options = {
                    type: "post",
                    url: url,
                    dataType: "json",
                    data: {data: JSON.stringify(sendData)},
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options, "/notify/alertPlatform");
            }

        })
    }
);
define(
    '../epg2/EpgWeb.Task',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Task = (function () {
            var handler = function(data,callback){
                if (callback != null) {
                    callback.call(this, data);
                }
            }
            var getConfigType = function (typeName, callback, regName) {
                if (regName == null) {
                    regName = typeName;
                }
                return {
                    regName: regName,
                    options: {
                        type: "get",
                        url: EpgWeb.urlConfig.configs,
                        dataType: "json",
                        data: {type: typeName},
                        success: function(data){
                            handler.call(this, data,callback);
                        },
                        error: function(data){
                            handler.call(this, data,callback);
                        }
                    }
                }
            }

            var getChannel = function (regName,params) {
                return {
                    regName:regName,
                    options: {
                        type: "post",
                        url: EpgWeb.urlConfig.channelGet,
                        dataType: "json",
                        data: params
                    }
                }
            }
            return {
                getConfigType: getConfigType,
                getChannel:getChannel
            }
        })()
    }
);
define(
	'../ticket/Ticket',['require','exports','module'],function(require, exports, module){
		window.Ticket = window.Ticket || { version : '1.0' };
        Ticket.Constant = {
            baseApiUrl: "/api/",
            thirdUrl_query_user:"http://lego.iqiyi.com/external/auth/auth-api/services/user/search",
            thirdUrl_channel_type: "http://lego.iqiyi.com/suggest/operation",
            devMode: auth.dev()
        }
        Ticket.urlConfig = (function () {
            var useUrl = Ticket.Constant.baseApiUrl;
            var redirectUrl = useUrl + "redirect";
            var getTicketDataListUrl = useUrl + "ticket/data/list";
            var getCheckListUrl =  useUrl + "ticket/checkList";
            var assignUrl =  useUrl + "ticket/data/assign";
            var configs =  useUrl + "ticket/configs/query";
            var logUrl = useUrl + "ticket/logList";
            var getChannelListUrl = useUrl + "channel/list";
            return {
                redirectUrl:redirectUrl,
                getTicketDataListUrl:getTicketDataListUrl,
                getCheckListUrl:getCheckListUrl,
                configs:configs,
                assignUrl:assignUrl,
                logUrl:logUrl,
                getChannelListUrl:getChannelListUrl
            }
        })()
	}
);
define(
    '../ticket/Ticket.Grid',['require','exports','module'],function (require, exports, module) {

        Ticket.Grid = function (options) {
            this.dao = Ticket.Dao;
            this.config = Ticket.Config;
            this.util = Ticket.Util;
            this.task = Ticket.Task;
            this.options = options || {};
        };

        Com.inherits(Ticket.Grid, Ancestor.Grid).extend({
            doInit: function () {
                var self = this;
                self.$grid = self.options.$grid;
                self.$logGrid = self.options.$logGrid;
                var taskArr = [];
                taskArr.push(self.task.getConfigType(self.dao.cfgName.logType));
                taskArr.push(self.task.getConfigType(self.dao.cfgName.workType));
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.startGrid();
                    var test = Com.url.getParameter("test");
                    if (test == "1") {
                        Ticket.Util.transToDevMode();
                    }
                })
                EpgWeb.ajaxQueue.startLoad();
            },

            startGrid: function () {
                var self = this;
                self.initTicketDataGrid();
                self.initHistoryGrid();
                self.initLogGrid();
                self.initDlg();
                self.bindEvent();
                self.initSuggest();
                $("button[name=queryBtn]").click();
            },
            bindEvent: function () {
                var self = this;
                $("button[query-sql]").bind("click", function (event) {
                    var $target = $(event.currentTarget);
                    $("button[type=reset]").click();
                    var params = Ticket.Util.buildTicketDataParams($target.attr("query-sql").split(","), $target.attr("query-value").split(","), $target.attr("quick"))
                    if ($target.attr("quick") == "true") {
                        Ticket.Util.fillBasicForm(params);
                        $("button[name=queryBtn]").click();
                    } else {
                        Ticket.Util.getTicketDataList(params);
                    }
                });
                $("button[name=queryBtn]").bind("click", function (event) {
                    var params = self.getParams();
                    Ticket.Util.getTicketDataList(params);
                })

            },
            getParams: function () {
                var self = this;
                var params = {};
                var $elements = $.makeArray($("form[name=basicFrm]").prop('elements'));
                $.each($elements, function () {
                    if ($(this).val() == "") {
                        return true;
                    }
                    if (this.name == "deadline") {
                        self.decodeDeadline(params, $(this));
                    } else {
                        params[this.name] = $(this).val();
                    }
                });
                if ("EQS_reporter" in  params) {
                    params["EQS_reporter"] = $("input[name=EQS_reporter]").suggest("getValue");
                }
                if ("EQS_executor" in  params) {
                    params["EQS_executor"] = $("input[name=EQS_executor]").suggest("getValue");
                }
                return params;
            },
            decodeDeadline: function (params, jElement) {
                if (jElement.attr("decodemode") == "function") {
                    var selectValue = jElement.val();
                    var paramsArr =  Ticket.Util.decodeDeadline(selectValue);
                    $.each(paramsArr,function(i,obj){
                        params[obj.key] = obj.result;
                    })
                }
            },
            initTicketDataGrid: function () {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TICKET_DATA_LIST, self.config.TABLE_COLMODEL_CONFIG);
                self.$grid.jqGrid(gridConfig);
            },
            initHistoryGrid: function () {
            },
            initLogGrid: function () {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_LOG, self.config.TABLE_COLMODEL_CONFIG);
                self.$logGrid.jqGrid(gridConfig);
            },
            initDlg: function () {
                var self = this;
                // self.initCreateTicketDlg();
                self.initHistoryDlg();
                self.initWorkerDlg();
                self.initDlgCheckList();
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
            },
            initDlgCheckList: function () {
                $("#dlg_checkList").dialog({
                    title: "直播检查列表",
                    autoOpen: false,
                    width: 500,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    open: function () {
                        $("#form_checkList")[0].reset();
                        $("#form_checkList").find("a.qui-tag-remove").click();
                        $("#form_checkList").find("input[name=project_workers]").suggest("setValue", "");
                    }
                });
            },
            initCreateTicketDlg: function () {
                $("#createDiv").dialog({
                    title: "直播工单创建",
                    autoOpen: false,
                    width: 500,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    open: function () {
                        $("input[name=programQipuId]").removeAttr("readonly");
                        $("input[name=programQipuId]").val("");
                        Ticket.Model.clearModelView();
                    }
                });
            },
            initHistoryDlg: function () {
                $("#ticketLogDiv").dialog({
                    title: "历史记录",
                    autoOpen: false,
                    width: 900,
                    height: 600,
                    modal: true,
                    dialogClass: 'alert'
                });
            },
            initWorkerDlg: function () {
                $("#workerDiv").dialog({
                    title: "分配任务",
                    autoOpen: false,
                    width: 480,
                    modal: true,
                    dialogClass: 'alert'
                });
                var self = this;
                var workerData = self.dao.getWorkers();
                var selectJDom = $("select[name=assign_worker]");
                $("<option value=''>请选择</option>").appendTo(selectJDom);
                if (workerData.data != null) {
                    $.each(workerData.data, function (index, obj) {
                        $("<option>", {
                            value: obj.val,
                            html: obj.desc
                        }).appendTo(selectJDom);
                    });
                }
                $("button[name=worker-dlg-cancel]").bind("click", function (event) {
                    $("#workerDiv").dialog("close");
                })
                $("button[name=worker-dlg-ok]").bind("click", function (event) {
                    var selectWorker = $("select[name=assign_worker]").val();
                    if (selectWorker.length == 0) {
                        return;
                    }
                    var ticketId = parseInt($("input[name=assign_ticket_id]").val());
                    Ticket.Util.assignTask(ticketId, selectWorker);
                    $("#workerDiv").dialog("close");
                })
            },
            initSuggest: function () {
                var emailSuggest = {
                    options: {
                        source: Ticket.urlConfig.redirectUrl,
                        method: "post",
                        multiple: false,
                        getParam: function (term) {
                            var requestData = {url: Ticket.Constant.thirdUrl_query_user, type: "get", params: {email: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["email"];
                                itemData[options.labelKey] = item["userName"];
                                itemData["email"] = item["email"];
                                itemData["uid"] = item["uid"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label + "(" + item.id + ")";
                        }
                    }
                }
                $("input[name=EQS_reporter]").suggest(emailSuggest.options);
                $("input[name=EQS_executor]").suggest(emailSuggest.options);

            },
            bindEventDebug: function () {
                $("button[name=create_ticket_data]").bind("click", function (event) {
                    $("#createDiv").dialog("open");
                })
                $("input[name=programQipuId]").focusout(function (event) {
                    var queryWord = $("input[name=programQipuId]").val();
                    if (queryWord.length > 2 && queryWord.endsWith("23")) {
                        if (Ticket.Model.underUsing()) {
                            return;
                        }
                        var sendData = { qipuId: queryWord, deleteStatus: 0, liveType: 2, fromPath: "library", pageNo: 1, pageSize: 1}
                        Ticket.Model.clearModelView();
                        Ticket.Dao.sendAjax("/api/program/list", "post", sendData, function (rdata) {
                            if (rdata.code === "A00000" && rdata.data.result.length > 0) {
                                $("input[name=programQipuId]").attr("readonly", true);
                                Ticket.Model.fillModelHtml(rdata.data.result[0]);
                            } else {
                                EpgWeb.Plugin.showTips({type: "error", content: rdata.msg == null ? "请求失败" : rdata.msg  });
                            }
                        }, "/program/list");
                    }
                })

            }
        });

    }
);
define('../ticket/Ticket.Config',['require','exports','module'],function (require, exports, module) {

    Ticket.Config = $.extend({}, {}, {
        TABLE_COLMODEL_CONFIG: {
            //oaDocNo
            id: {
                name: "id",
                index: 'id',
                title: false,
                width: 100,
                align: "center",
                sortable: false,
                hidden:true
            },
            oaDocNo: {
                name: "oaDocNo",
                index: 'oaDocNo',
                title: false,
                width: 150,
                align: "center",
                sortable: false
            },
            entityId: {
                name: "entityId",
                index: 'entityId',
                title: false,
                width: 100,
                sortable: false,
                align: "center"
            },
            dataType: {
                name: "dataType",
                index: 'dataType',
                title: false,
                width: 70,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Ticket.Util.formatter.dataType(v, o, r);
                }
            },
            title: {
                name: "title",
                index: 'title',
                title: false,
                width: 200,
                sortable: false,
                align: "center"
            },
            reporter: {
                name: "reporter",
                index: 'reporter',
                title: false,
                width: 140,
                sortable: false,
                formatter: function (v, o, r) {
                    return Ticket.Util.formatter.reporter(v, o, r);
                }
            },
            executor: {
                name: "executor",
                index: 'executor',
                title: false,
                width: 140,
                sortable: false,
                formatter: function (v, o, r) {
                    return Ticket.Util.formatter.executor(v, o, r);
                }
            },
            oaDocEditorStatus: {
                name: "oaDocEditorStatus",
                index: 'oaDocEditorStatus',
                title: false,
                width: 135,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Ticket.Util.formatter.oaDocEditorStatus(v, o, r);
                }
            },
            ticket_status: {
                name: "status",
                index: 'status',
                title: false,
                width: 80,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Ticket.Util.formatter.ticket_status(v, o, r);
                }
            },
            operator_ticket_data: {
                name:"operator_ticket_data",
                title: false,
                width: 120,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Ticket.Util.formatter.operator_ticket_data(v, o, r);
                }
            },
            ticket_detail:{
                name: "detail",
                index: 'detail',
                title: false,
                width: 300,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Ticket.Util.formatter.detail(v, o, r);
                }
            },
            deadline:{
                name: "deadline",
                index: 'deadline',
                title: false,
                width: 135,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Ticket.Util.formatter.deadline(v, o, r);
                }
            },
            log_id: {
                name: 'id',
                index: 'id',
                title: false,
                sortable: false,
                hidden: true
            },
            log_addTime:{
                name: 'addTime',
                index: 'addTime',
                sortable: false,
                title: false,
                width: 150,
                align: 'center',
                hidden:true
            },
            log_user: {
                name: 'user',
                index: 'user',
                sortable: false,
                title: false,
                width: 150
            },
            log_type: {
                name: 'type',
                index: 'type',
                sortable: false,
                title: false,
                width: 120,
                formatter: function (v, o, r) {
                    return Ticket.Util.formatter.log_type(v,o, r);
                }
            },
            log_descr: {
                name: "descr",
                index: 'descr',
                title: false,
                width: 450,
                sortable: false
            }
        },
        TICKET_DATA_LIST: {
            url: Ticket.urlConfig.getTicketDataListUrl,
            loadBeforeSend: function (xhr, settings) {
                var auth = Ancestor.Util.getAuth("/ticket/data/list");
                xhr.setRequestHeader('Sign', auth.sign);
                xhr.setRequestHeader("Time", auth.clientTime);
                xhr.setRequestHeader("From", auth.from);
                return true;
            },
            caption: "工单列表",
            multiselect: false,
            loadtext: '加载中...',
            loadui: 'block',
            rowNum: 10,
            mtype: "post",
            datatype: "local",
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            colNames: ["工单号","oa单号", "项目类型", "主题",  "状态", "内容","发起人", "执行人", "OA审核状态", "剩余时间", "操作"],
            colModel: ['id',"oaDocNo", "dataType", "title",  "ticket_status","ticket_detail", "reporter" , "executor" , "oaDocEditorStatus" ,"deadline", "operator_ticket_data"],
            pager: "#pager"
        },

        TABLE_LOG: {
            url: Ticket.urlConfig.logUrl,
            loadBeforeSend: function (xhr, settings) {
                var auth = Ancestor.Util.getAuth("/ticket/logList");
                xhr.setRequestHeader('Sign', auth.sign);
                xhr.setRequestHeader("Time", auth.clientTime);
                xhr.setRequestHeader("From", auth.from);
                return true;
            },
            multiselect: false,
            loadtext: '加载中...',
            loadui: 'block',
            rowNum: 50,
            mtype: "post",
            datatype: "local",
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            colNames: ["ID", "操作时间", "人员", "动作", "备注"],
            colModel: ['log_id', "log_addTime", "log_user" , "log_type" , "log_descr"],
            pager: "#log_pager"
        },

        CHECK_LIST_LEN:6,
        CODE_SUC :"A00000"

    });
});
define('../ticket/Ticket.Util',['require','exports','module'],function (require, exports, module) {
    Ticket.Util = $.extend(true, {}, EpgWeb.Util, {
        formatter: {
            ticket_status: function (v, o, r) {
                switch (v) {
                    case 999:
                        return "处理终止";
                    case 1:
                        return "处理完成";
                    case 0:
                        return "待处理";
                    default :
                        return "unknown " + v;
                }
            },
            operator_ticket_data: function (v, o, r) {
                var htmlArr = [];
                var isOwner = Ticket.Util.isCurrentUser(r.executor);
//                if (!isOwner) {
//                    htmlArr.push("<a href='javascript:;' onclick='Ticket.Util.assignTask(" + r.id + ",\"" + Ticket.Util.getCurrentUserObj().id + "\")' >分配给我</a>  ");
//                } else {
//                    if (r.dataType == 1) {
//                        htmlArr.push("<a href='javascript:;' onclick='Ticket.Util.doTaskCheck(" + r.id + ")' >检查</a>  ");
//                    }
//
//                }
//                htmlArr.push("<a href='javascript:;' onclick='Ticket.Util.assignTask(" + r.id + ")' >分配</a>  ");
//                htmlArr.push("<a href='javascript:;' onclick='Ticket.Util.openHistory(" + r.id + ")' >详细</a>  ");
                try {
                    var jsonObj = JSON.parse(r.detail)
                    if (jsonObj.hasOwnProperty("channelQipuId")) {
                        htmlArr.push("<a href='javascript:;' onclick='Ticket.Util.openStream(" + jsonObj.channelQipuId + ")' >直播流</a>  ");
                    }
                } catch (e) {
					console.log(e);
                }


                // htmls.push('<a href="./live_stream.html?qipuId='+ r.qipuId+'&id=' + r.id + '&name=' +  encodeURIComponent(name.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">")) + '&livetype=' + r.liveType + '&universalcode=' + r.universalCode.toLowerCase() + '" class="' + stream + '" target="_blank">直播流管理</a>');
                return htmlArr.join(" ");
            },
            reporter: function (v, o, r) {
                if (v == "_system_") {
                    return "";
                }
                return v;
            },
            executor: function (v, o, r) {
                if (v == null) {
                    return "";
                }
                var ret = "";
                var response = Ticket.Dao.getWorkers();
                if (response != null && response.data != null) {
                    $.each(response.data, function (idx, element) {
                        if (element.val == v) {
                            ret = element.desc;
                            return false;
                        }
                    })
                }
                return ret;
            },
            dataType: function (v, o, r) {
                switch (v) {
                    case 1:
                        return "直播工单";
                    default :
                        return "unknown " + v;
                }
            },
            oaDocEditorStatus: function (cellvalue, o, rowObject) {
                var ret = "";
                switch (cellvalue) {
                    case "unchecked":
                        ret = "待审核";
                        break;
                    case "checked":
                        ret = "总编室已确认";
                        break;
                    case "interrupt":
                        ret = "<span style='color: red'>中断</span>";
                        break;
                    default :
                        ret = "---"
                        break;
                }
                if (ret != "---") {
                    ret = "<a target='_blank' href='" + rowObject.oaDocUrl + "'>" + ret + "</a>"
                }
                return ret;
            },
            detail: function (v, o, r) {
                //   return "";
                return Ticket.Model.parseFormat(r.dataType, v);
            },
            deadline: function (v, o, r) {
                var ret = v;
                if (r.status == 0) {
                    var original = new Date(v.replace(/-/g, "/")).getTime();
                    var current = new Date().getTime();
                    var second = (original - current) / 1000 >> 0
                    if (second < 0) {
                        ret = "已过期";
                    } else {
                        ret = Ticket.Util.tranDurationFormat(second);
                        if (second < 600) {
                            ret = "<span style='color: red'>" + ret + "</span>"
                        }
                    }
                } else {
                    ret = "------";
                }
                return ret;
            },
            log_type: function (cellvalue, options, rowObject) {
                var ret = "";
                var enumNameData = Ticket.Dao.logType();
                $.each(enumNameData.data, function (index, element) {
                    if (cellvalue == element.key) {
                        ret = element.desc;
                        return false;
                    }
                })
                return ret;
            }
        },
        buildTicketDataParams: function (sqlArr, sqlValueArr, fillMode) {
            var length = sqlArr.length;
            var params = {};
            var tempValue = null;
            for (var i = 0; i < length; i++) {
                tempValue = sqlValueArr[i];
                if (sqlValueArr[i] === "currentUser()") {
                    tempValue = fillMode == "true" ? Ticket.Util.getCurrentUserObj() : Ticket.Util.getCurrentUser();
                }
                params[sqlArr[i]] = tempValue;
            }
            return params;
        },
        getCurrentUser: function () {
            return auth.baseInfo.authInfo.email
        },
        getCurrentUserObj: function () {
            return  {id: auth.baseInfo.authInfo.email, label: auth.baseInfo.authInfo.userName}
        },
        fillBasicForm: function (params) {
            if ("EQS_reporter" in  params) {
                $("input[name=EQS_reporter]").suggest("setValue", params["EQS_reporter"]);
            }
            if ("EQS_executor" in  params) {
                $("input[name=EQS_executor]").suggest("setValue", params["EQS_executor"]);
            }
            if ("EQI_status" in params) {
                $("select[name=EQI_status]").val(params["EQI_status"]);
            }
        },
        getTicketDataList: function (params) {
            console.log(JSON.stringify(params));
            if ("EQL_id" in params) {
                if (!EpgWeb.Plugin.Validate.checkNum(params["EQL_id"])) {
                    EpgWeb.Plugin.showTips({content: "参数错误", type: "error"});
                    return;
                }
            }

            $("#listGrid").jqGrid('setGridParam', {
                page: 1,
                datatype: "json",
                postData: {paramsObj: JSON.stringify(params), orderObj: JSON.stringify({order: "asc", orderBy: "deadline"})}
            }).trigger('reloadGrid');
        },
        bindFoldDiv: function () {
            $("span[name=span_fold]").css({cursor: "pointer"});
            $("span[name=span_extend]").css({cursor: "pointer"});
            $("span[name=span_fold]").bind("click", function (event) {
                var $target = $(event.currentTarget);
                $target.parent().find("span[name=span_extend]").show();
                $target.hide();
                var name = $target.parent().attr("foldTarget");
                if (name == null || name.length < 1) {
                    name = "folder";
                }
                $target.parent().parent().find("div[name=" + name + "]").hide();
            });
            $("span[name=span_extend]").hide();
            $("span[name=span_extend]").bind("click", function (event) {
                var $target = $(event.currentTarget);
                $target.parent().find("span[name=span_fold]").show();
                $target.hide();
                var name = $target.parent().attr("foldTarget");
                if (name == null || name.length < 1) {
                    name = "folder";
                }
                $target.parent().parent().find("div[name=" + name + "]").show();
            });
        },
        checkSubmit: function () {
            var params = {};
            var elementArr = $.makeArray($("#dlg_checkList").find("input[type=radio]:checked"));
            if (Ticket.Config.CHECK_LIST_LEN > elementArr.length) {
                EpgWeb.Plugin.showTips({content: "尚有项目未检查", type: "error"});
                return
            }
            $.each(elementArr, function (i, element) {
                params[element.name] = element.value;
            })
            $("#dlg_checkList").dialog("close");
        },
        checkClosed: function () {
            $("#dlg_checkList").dialog("close");
        },
        openDlgCheckList: function () {
            var self = this;
            Ticket.Dao.getCheckList({dataId: Ticket.Dao.cfgName.entityId }, function (rdata) {
                if (rdata != null && rdata.code == Ticket.Config.CODE_SUC) {
                    self.fillDataCheckList(rdata.data);
                    $("#dlg_checkList").dialog("open");
                }
            });
        },
        fillDataCheckList: function (dataEntity) {
            //  $("#dlg_checkList").find("")
        },
        transToDevMode: function () {
            $("div[name=in_dev_div]").css({display: "inline-block"})
            $("#listGrid").setGridParam().showCol("operator_ticket_data").trigger("reloadGrid");
        },
        isCurrentUser: function (email) {
            return email == this.getCurrentUserObj().id;
        },
        decodeDeadline: function (selectValue) {
            var self = this;
            var startIndex = 0;
            var objArr = [];
            var nowTime = new Date();
            var nowValue = Ticket.Util.formatDateTimeFormat(nowTime)
            while (startIndex < selectValue.length) {
                var obj = {key: "", value: "", result: ""}
                var keySplit = selectValue.indexOf("=", startIndex);
                var valueEnd = selectValue.indexOf(";", keySplit + 1);
                obj.key = selectValue.slice(startIndex, keySplit);
                if (valueEnd == -1) {
                    valueEnd = selectValue.length;
                }
                obj.value = selectValue.slice(keySplit + 1, valueEnd);
                startIndex = valueEnd + 1;
                if (obj.value == "now()") {
                    obj.result = nowValue;
                } else if (obj.value.startsWith("func")) {
                    obj.result = self.decodeTimeFun(obj.value.slice(5, obj.value.length - 1).split(","), nowTime)
                }
                objArr.push(obj);
            }
            return objArr;
        },
        decodeTimeFun: function (paramsArr, baseTime) {
            var type = paramsArr[0];
            var time = paramsArr[1] == "now()" ? baseTime : new Date(paramsArr[1]);
            var changeValue = parseInt(paramsArr[2]);
            var ret = null;
            switch (type) {
                case "addhour":
                    time.setTime(time.getTime() + changeValue * 1000 * 3600);
                    ret = this.formatDateTimeFormat(time)
                    break;
            }
            return ret;
        },
        openHistory: function (entityId) {
            $("#ticketLogDiv").dialog("open");
            $('#logList').jqGrid('setGridParam', {
                page: 1,
                datatype: "json",
                postData: {id: entityId}
            }).trigger('reloadGrid');
        },
        openStream: function (channelQipuId) {
            Ticket.Dao.getChannelDataList({qipuId: channelQipuId}, function (data) {
                if (data != null && data.code == "A00000") {
                    if (data.data.result.length == 1) {
                        var r = data.data.result[0];
                        var openUrl = "live_stream.html?qipuId=" + r.qipuId + "&id=" + r.id + '&name=' + encodeURIComponent(r.name.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">")) + '&livetype=' + r.liveType + '&universalcode=' + r.universalCode.toLowerCase();
                        window.open(openUrl);
                    }
                } else {
                    console.log("请求失败");
                }
            })
        },

        openAssignTaskDlg: function (entityId) {
            $("#workerDiv").dialog("open");
            $("input[name=assign_ticket_id]").val(entityId)
            $("select[name=assign_worker]").val("");
        },
        assignTask: function (entityId, email) {
            if (email == null) {
                this.openAssignTaskDlg(entityId);
            } else {
                Ticket.Dao.assignTask({id: entityId, executor: email}, function (data) {
                    if (data == null || data.code != Ticket.Config.CODE_SUC) {
                        EpgWeb.Plugin.showTips({type: "error", content: "请求失败：" + data.msg});
                    }
                    $("#listGrid").trigger("reloadGrid");
                })
            }
        },
        doTaskCheck: function (entityId) {
            var self = this;
            Ticket.Dao.getCheckList({dataId: entityId }, function (rdata) {
                if (rdata != null && rdata.code == Ticket.Config.CODE_SUC) {
                    self.fillDataCheckList(rdata.data);
                    $("#dlg_checkList").dialog("open");
                }
            });
        }

    });
});
define(
    '../ticket/Ticket.Dao',['require','exports','module'],function (require, exports, module) {

        Ticket.Dao = $.extend({}, EpgWeb.Dao, {
            getTicketDataList: function (sendData,handler) {
                this.sendAjax(Ticket.urlConfig.getTicketDataListUrl,"post",sendData,handler,"/ticket/data/list");
            },
            getCheckList: function (sendData,handler) {
                this.sendAjax(Ticket.urlConfig.getCheckListUrl,"post",sendData,handler,"/ticket/checkList");
            },
            logType: function () {
                return this.getDataByName(this.cfgName.logType);
            },
            getWorkers:function(){
                return this.getDataByName(this.cfgName.workType);
            },
            assignTask:function(sendData,handler){
                this.sendAjax(Ticket.urlConfig.assignUrl,"post",sendData,handler,"/ticket/data/assign");
            },
            // 获取单个频道数据
            getChannelDataList: function(data, handler) {
                this.sendAjax(Ticket.urlConfig.getChannelListUrl,"post",data,handler,"/channel/list");
            }
        });
        Ticket.Dao.cfgName = {
            logType:"ticket_log",
            workType:"ticket_worker"
        }
    }
);
define(
	'../ticket/Ticket.Action',['require','exports','module'],function(require, exports, module){

        Ticket.Action = (function() {
            var ticketGrid = null;
            function gridRun() {
                if (ticketGrid == null) {
                    ticketGrid = new Ticket.Grid($.extend(true, {
                        $grid: $("#listGrid"),
                        $logGrid:$("#logList")
                    }, {}));
                    ticketGrid.doInit();
                }
                console.log(' ticketGrid run ');
            }
            var  liveEditHtml = null;
            function liveEditRun() {
                if (liveEditHtml == null) {
                    liveEditHtml = new Ticket.LiveEdit($.extend(true, {

                    }, {}));
                    liveEditHtml.doInit();
                }
                console.log(' liveEditRun run ');
            }
            return {
                gridRun: gridRun,
                liveEditRun:liveEditRun
            }
        })();
	}
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Program.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-03-01
 */
define(
    '../ticket/Ticket.Task',['require','exports','module'],function (require, exports, module) {
        Ticket.Task = (function () {
            var handler = function(data,callback){
                if (callback != null) {
                    callback.call(this, data);
                }
            }
            var getConfigType = function (typeName, callback, regName) {
                if (regName == null) {
                    regName = typeName;
                }
                return {
                    regName: regName,
                    options: {
                        type: "get",
                        url: Ticket.urlConfig.configs,
                        dataType: "json",
                        data: {paramsObj:JSON.stringify({EQS_type: typeName})} ,
                        success: function(data){
                            handler.call(this, data,callback);
                        },
                        error: function(data){
                            handler.call(this, data,callback);
                        }
                    }
                }
            }

            return {
                getConfigType: getConfigType
            }
        })()
    }
);
define('../ticket/Ticket.Model',['require','exports','module'],function (require, exports, module) {
    Ticket.Model = (function () {
        var divPanel = $("#liveEpisodeDiv");

        function createModelHtml() {

        }

        function getSubmitData() {

        }

        function fillModelHtml(rdata) {
            divPanel.show();
            divPanel.find("span[name=pname]").html(rdata.pname);
            divPanel.find("span[name=time_range]").html(rdata.startPlayTime + "~" + rdata.endPlayTime);
            divPanel.find("span[name=boss_status]").html(transBossStatus(rdata.bossStatus));
            divPanel.find("span[name=episodeGrade]").html(transEpisodeGrade(rdata.episodeGrade));
        }

        function transBossStatus(bossStatus) {
            var enumValue = "";
            switch (bossStatus) {
                case "FREE":
                    enumValue = "免费";
                    break;
                case "PAIED_NOT_AVAILABLE":
                    enumValue = "<span style='color: red'>付费未划价</span>";
                    break;
                case "PAIED_AVAILABLE":
                    enumValue = "<span style='color: red'>付费已划价</span>";
                    break;
                default:
                    enumValue = "Unknown " + bossStatus;
                    break;
            }
            return enumValue;
        }

        function transEpisodeGrade(episodeGrade) {
            var rest = episodeGrade % 10;
            var level = parseInt((episodeGrade -100) / 10);
            var retValue = String.fromCharCode(65+level)+"类";
            switch (rest) {
                case 1:
                    retValue +="一";
                    break;
                case 2:
                    retValue +="二";
                    break;
                case 3:
                    retValue +="三";
                    break;
            }
            retValue+="级"
            return retValue;
        }
        function transTest(test){
            return test == 0 ? "正式":"测试";
        }

        function clearModelView() {
            divPanel.hide();
        }

        function underUsing() {
            return divPanel.is(":visible")
        }

        function parseFormat(type,rdata){
            if(type == 1){
                return decodeLiveDetail(rdata );
            }
            return rdata;
        }

        function decodeLiveDetail(rdata){
            var jsonObj = JSON.parse(rdata)
            var htmlArr =[];
            htmlArr.push("频道奇谱ID:"+(jsonObj.channelQipuId||"")+","+"节目奇谱ID:"+jsonObj.qipuId);
            htmlArr.push("节目时间:"+jsonObj.startPlayTime+"~"+jsonObj.stopPlayTime);
 //           htmlArr.push(transBossStatus(jsonObj.bossStatus )+","+transEpisodeGrade(jsonObj.episodeGrade )+","+ transTest(jsonObj.test))
           return htmlArr.join("<br>")
        }
        return {
            createModelHtml: createModelHtml,
            getSubmitData: getSubmitData,
            fillModelHtml: fillModelHtml,
            clearModelView: clearModelView,
            underUsing: underUsing,
            parseFormat:parseFormat,
            decodeLiveDetail:decodeLiveDetail
        }
    })()
});
/**
 * Copyright 2015 Qiyi.com All rights reserved.
 *
 * file: epg.js
 * path: js-src/
 * description: epg业务合并文件，通过该文件引入业务功能模块的js文件
 *              配置文件将用来生成合并文件
 * author: jiegang@qiyi.com
 * date: 2015-1-6
 */
define(
    'ticket', [
        "../entrance_ticket/Ancestor",
        "../entrance_ticket/Ancestor.Auth",
        "../entrance_ticket/Ancestor.Grid",
        "../entrance_ticket/Ancestor.Config",
        "../entrance_ticket/Ancestor.Util",
        "../entrance_ticket/Ancestor.Dao",
        "../epg2/EpgWeb",
        "../epg2/EpgWeb.Util",
        "../epg2/EpgWeb.Plugin",
        "../epg2/EpgWeb.Dao",
        "../epg2/EpgWeb.Task",
        "../ticket/Ticket",
        "../ticket/Ticket.Grid",
        "../ticket/Ticket.Config",
        "../ticket/Ticket.Util",
        "../ticket/Ticket.Dao",
        "../ticket/Ticket.Action",
        "../ticket/Ticket.Task",
        "../ticket/Ticket.Model"
    ],

    function() {
        console.log('ticket load done:', 'ticket');
        if (SystemDialog && SystemDialog.initSystemDialog) {
            SystemDialog.initSystemDialog();
        }
    }
);

